#!/bin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc.	 All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

#
# Start script for the SPARC-Enterprise DSCP service.
#

. /lib/svc/share/smf_include.sh

OPL=SUNW,SPARC-Enterprise
OPL_LIB=/usr/platform/${OPL}/lib
DM2S_DEVICE=/dev/dm2s0
PPP_OPTIONS=${OPL_LIB}/dscp.ppp.options
DSCP_IFNAME=/var/run/dscp.ifname
PRTDSCP=/usr/platform/${OPL}/sbin/prtdscp
PLATFORM=`/sbin/uname -i`
SLEEP=/bin/sleep
PKILL=/bin/pkill

LD_LIBRARY_PATH=/lib:${OPL_LIB}; export LD_LIBRARY_PATH

# This service can only run on OPL.
if  [ "${PLATFORM}" != "${OPL}" ]; then
	exit $SMF_EXIT_ERR_CONFIG
fi

case "$1" in
'start')

	if [ ! -x /usr/bin/pppd ]; then
		exit $SMF_EXIT_ERR_CONFIG
	fi

	if [ ! -c $DM2S_DEVICE ]; then
		exit $SMF_EXIT_ERR_CONFIG
	fi

	if [ ! -f $PPP_OPTIONS ]; then
		exit $SMF_EXIT_ERR_CONFIG
	fi
		
	SUCCESS=0
	for UNIT in 0 1 2 3 4 5 6 7 8 9; do
		/usr/bin/pppd $DM2S_DEVICE unit $UNIT file $PPP_OPTIONS
		if [ ! "$?" = "1" ]; then
			echo "sppp$UNIT" > $DSCP_IFNAME
			SUCCESS=1
			break
		fi
	done

	if [ $SUCCESS -ne 1 ]; then
		exit $SMF_EXIT_ERR_FATAL
	fi

	# Wait for the DSCP link to come up, but only for 30 seconds
	for RETRY in 0 1 2 3 4 5; do
		${PRTDSCP} >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			exit $SMF_EXIT_OK
		fi
		${SLEEP} 5
	done
	
	# Stop pppd before we return failure
	${PKILL} -TERM -f "pppd ${DM2S_DEVICE}"
	${SLEEP} 1
	${PKILL} -KILL -f "pppd ${DM2S_DEVICE}"
	rm -f $DSCP_IFNAME
	exit $SMF_EXIT_ERR_FATAL
	;;

'stop')
	# First try SIGTERM and then SIGKILL
	${PKILL} -TERM -f "pppd ${DM2S_DEVICE}"
	${SLEEP} 1
	${PKILL} -KILL -f "pppd ${DM2S_DEVICE}"
	rm -f $DSCP_IFNAME
	exit $SMF_EXIT_OK
	;;
esac
